package com.ling.common.library.utils

import android.content.Context
import android.view.inputmethod.InputMethodManager
import android.widget.EditText

/**
 * @author Ling
 * @date :2024/7/17 15:29
 */
object SoftKeyboardUtil {
    fun showSoftInput(view: EditText?) {
        view?.requestFocus()
        val imm = view?.context?.getSystemService(Context.INPUT_METHOD_SERVICE)
        if(imm == null) return
        imm as InputMethodManager
        if (imm.isActive) {
            imm.showSoftInput(view, 0)
            view.text?.let {
                if(it.isNotEmpty()){
                    view.setSelection(it.length)
                }
            }
        }
    }

    /**
     * 关闭软键盘
     *
     * @param view 上下文
     */
    fun closeSoftInput(view: EditText?) {
        view?.clearFocus()
        val imm = view?.context?.getSystemService(Context.INPUT_METHOD_SERVICE)
        if(imm == null) return
        imm as InputMethodManager
        if (imm.isActive) {
            imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }
}